package org.fin.minicat.compile;

import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class WebappClassLoader extends ClassLoader {

  private final String sourceRoot;

  private final ClassLoader parent;

  public WebappClassLoader(ClassLoader parent, String sourceRoot) {
    super(parent);
    this.parent = parent;
    this.sourceRoot = "file://" + sourceRoot;
  }

  @Override
  protected Class<?> findClass(String name) {
    String classLocation = sourceRoot + name.replace('.', '/') + ".class";
    try {
      Path path = Paths.get(new URI(classLocation));
      byte[] bytes = Files.readAllBytes(path);
      return defineClass(name, bytes, 0, bytes.length);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
